package de.sonnemann_it.helden_software.heldenbogen.originalpdf;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;
import javax.swing.border.EmptyBorder;


@SuppressWarnings("serial")
public class DownloadDialog extends JDialog {

	private final JPanel contentPanel = new JPanel();
	private String[] urls = {};
	private String outputPath;
	private final JProgressBar currentProgress = new JProgressBar();
	private JLabel currentFilename;
	private JProgressBar totalProgress;
	private SwingWorker<Integer, Integer> worker;
	private boolean downloadResult;
	
	/**
	 * Create the dialog.
	 */
	public DownloadDialog() {
		setModalityType(ModalityType.APPLICATION_MODAL);
		setResizable(false);
		setModal(true);
		setBounds(100, 100, 340, 221);
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		contentPanel.setLayout(new GridLayout(4, 1, 0, 0));
		{
			currentFilename = new JLabel("Aktuelle Datei");
			contentPanel.add(currentFilename);
		}
		contentPanel.add(currentProgress);
		{
			JLabel totalProgress = new JLabel("Absolut:");
			contentPanel.add(totalProgress);
		}
		{
			totalProgress = new JProgressBar();
			contentPanel.add(totalProgress);
		}
	}
	
	public DownloadDialog(String[] urls, String outputPath){
		this();
		this.urls = urls;
		this.outputPath = outputPath;
		
	}
		
	
	public boolean downloadUrls() {
		

		worker = new SwingWorker<Integer, Integer>(){
			boolean allOk = true;
			@Override
			protected Integer doInBackground() throws Exception {
				getTotalProgress().setValue(0);
				getTotalProgress().setMaximum(getUrls().length);
				for (String url : getUrls()) {
					try {
						downloadUrl(url);
						getTotalProgress().setValue(getTotalProgress().getValue() + 1);
					} catch (Exception ex) {
						Logger.getLogger(DownloadDialog.class.getName()).log(Level.SEVERE,
								null, ex);
						allOk = false;
						return 0;
					}
				}
				return 0;
			}
			
			@Override
			protected void done() {
				DownloadDialog.this.setDownloadResult(allOk);
				DownloadDialog.this.setVisible(false);				
			}
					
		};
		worker.execute();
		setVisible(true);
		return getDownloadResult();
	}
	
	private boolean getDownloadResult() {
		return downloadResult;
	}

	protected void setDownloadResult(boolean allOk) {
		downloadResult = allOk;
	}

	private void downloadUrl(String uri) throws Exception {
		URL url = new URL(uri);
		URLConnection connection = url.openConnection();
		getCurrentProgress().setValue(0);
		getCurrentProgress().setMaximum(connection.getContentLength());
		String fileName = uri.substring( uri.lastIndexOf('/') + 1);
		getCurrentFilename().setText(fileName);
		FileOutputStream fos = new FileOutputStream(getOutputPath() + "/" + fileName);
		byte[] buffer = new byte[4096];
		int read = 0;
		InputStream is = connection.getInputStream();
		while ((read = is.read(buffer)) != -1) {
			getCurrentProgress().setValue( getCurrentProgress().getValue() + read );
			fos.write(buffer, 0, read);
			DownloadDialog.this.repaint();
		}
		fos.close();
		is.close();
		
	}

	public String[] getUrls() {
		return urls;
	}

	public void setUrls(String[] urls) {
		this.urls = urls;
	}

	public String getOutputPath() {
		return outputPath;
	}

	public void setOutputPath(String outputPath) {
		this.outputPath = outputPath;
	}
	
	protected JLabel getCurrentFilename() {
		return currentFilename;
	}
	protected JProgressBar getTotalProgress() {
		return totalProgress;
	}
	protected JProgressBar getCurrentProgress() {
		return currentProgress;
	}
}
